import router, {constantRoutes} from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import {getToken, setTenant, setToken} from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/auth-redirect', '/certificate', '/nursingRecord'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
    // set page title
    document.title = getPageTitle(to.meta.title)

    // determine whether the user has logged in
    const hasToken = getToken()
    if (hasToken) {
        if (to.path === '/login') {
            // if is logged in, redirect to the home page
            next({ path: '/' })
            NProgress.done() // hack: https://github.com/PanJiaChen/vue-element-admin/pull/2939
        } else {
            // determine whether the user has obtained his permission roles through getInfo
          if(store.state.user.roles.length == 0){
            try {
              // get user info
              await store.dispatch('user/getInfo')

              const routerList = constantRoutes.concat(store.state.user.routerListDA)
              router.addRoutes(routerList)

              // set the replace: true, so the navigation will not leave a history record
              next({...to, replace: true })
              NProgress.done()
            } catch (error) {
              // remove token and go to login page to re-login
              await store.dispatch('user/resetToken')
              Message.error(error || 'Has Error')
              next(`/login?redirect=${to.path}`)
              NProgress.done()
            }
          }else{
            next();
          }
        }
    } else {
        /* has no token*/
      if (whiteList.indexOf(to.path) !== -1) {
        // in the free login whitelist, go directly
        if(to.fullPath.indexOf("loginflag")!=-1) {
          //先判断是否包含单点验证的参数
          const params = to.fullPath.split("?")[1].split("&");
          const paramMap = new Map();
          params.map(v => (
            paramMap.set(v.split("=")[0], v.split("=")[1])
          ));
          //获取用户的唯一标识，用工号作为唯一标识 ,首次登陆为’-‘
          const loginid =paramMap.get("loginid");
          const captcha =paramMap.get("captcha");
          const loginflag=  paramMap.get("loginflag")
          //将单点的状态放入到store中，前台登录时判断是否是单点登录，如果是需要调用单点的登录注册接口
          store.commit('user/SET_ssoStatus', loginid+"+"+captcha);
          //单点登录中已经注册过了，需要调用单点登录的验证接口
          if(loginid!='-'){
            var loginVerifyData= await store.dispatch('user/loginVerify', {
                loginId:loginid,captcha:captcha
              }
            );
            if(loginVerifyData.code==200){
              const  loginData =await store.dispatch('user/findUserByWorkNumber', {
                loginid: loginid
              });
              //将用户的id放入的store中
              if(loginData.code==200){
                store.commit('user/SET_TOKEN', loginData.user.id)
                setToken(loginData.user.id)
                setTenant(loginData.user.tenantId)
                next({ path: '/' })
                NProgress.done();
              }else{
                next();
              }
            }else{
              next('/login');
            }
          }else{
            next();
          }
        }else{
          next()
        }
      } else {
        // other pages that do not have permission to access are redirected to the login page.
        next(`/login?redirect=${to.path}`)
      }
    }
})

router.afterEach(() => {
    // finish progress bar
    NProgress.done()
})
